<?php
require_once 'data_form'.EXT;

class savings extends data_form{

	function __construct(){
		parent::__construct();
		//unset($_SESSION['data']);
		$this->data['module_title']	=	'Savings';
	}
	
	function index()
	{
		$this->data['title']	=	'Savings';
		$row	=	null;
		$this->load->model(array('saving_model','explanation_model'));
		$rows	=	$this->saving_model->get_many_by(array('customer_id' => $_SESSION['customer']['id']));
		$exp	=	$this->explanation_model->get_by(array('customer_id' => $_SESSION['customer']['id'], 'data_form_id' => 1));
		//print_r($exp);
		if($_SERVER['REQUEST_METHOD'] == "GET" && $rows)
		{
			$temp	=	null;
			foreach($rows as $k => $v)
			{
				$temp=array(
					'customer_id'	=>	$v->customer_id,
					'amount_to_save'	=>	$v->amount_to_save,
					'years_to_go'	=>	$v->years_to_go,
					'id'			=>	$v->id
				);
				$data[] = $temp;
			}
			$_SESSION['data']	=	$data;
		}
		
		if($_SERVER["REQUEST_METHOD"]  == "POST")
		{
			$submit	=	$this->input->post('submit');
			foreach($this->input->post('amount') as $k => $v)
				{
					$temp = array(
						'customer_id'		=>	$_SESSION['customer']['id'],
						'amount_to_save'	=>	$v,
						'years_to_go'		=>	$_POST['years'][$k],
						'id'				=>	$_POST['id'][$k]
					);
					$data[]	=	$temp;
				}
			if(isset($_POST['btnCalculate']) && $_POST['btnCalculate'] == 'Calculate'){
				
				//close form
				//echo "<script>window.close();</script>";
				$_SESSION['data']	=	$data;
				//print_r($data);
			}
			else{
				
				if($exp){
					$this->explanation_model->update($exp->id,array('explanation' => $_POST['explanation']));	
				}
				else{
					$this->explanation_model->insert(array('explanation' => $_POST['explanation'], 'customer_id' => $_SESSION['customer']['id'], 'data_form_id' => 1));
				}
				//$data	=	$_SESSION['data'];
				$arr_id = null;
				foreach($data as $k => $v){
					//$v['explanation']	=	$_POST['explanation'];
					if($v['id'] == ''){
						unset($v['id']);
						$id	=	$this->saving_model->insert($v);
					}
					else
					{
						$id	=	$v['id'];
						unset($v['id']);
						$this->saving_model->update($id,$v);
					}
					$_SESSION['data'][$k]['id']	=	$id;
					$arr_id[]=$id;
				}
				
				//delete 
				if($arr_id){
					$re_del	=	$this->db->select()->from('savings')->where_not_in('id',$arr_id)->where('customer_id',$_SESSION['customer']['id'])->get()->result();
					if($re_del){
						foreach($re_del as $v){
							$this->saving_model->delete($v->id);
						}
					}
				}
				
				//close form
				//echo '<script>window.close();</script>';
				redirect(current_link());
				//
			}
			
		}
		$this->data['exp']	=	$exp;
		$this->data['rows']	=	(isset($_SESSION['data']) ? $_SESSION['data'] : null);
		$this->load->view("savings/index", $this->data);
	}

}